﻿using System.Collections.Concurrent;

namespace Tszy.Unlimited.Base.Collections;

/// <summary>
/// 线程安全的字典。
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
public class MonoConcurrentDictionary<TKey, TValue> : ConcurrentDictionary<TKey, TValue>
    where TKey : notnull
    where TValue : notnull
{
    /// <summary>
    /// 初始化。
    /// </summary>
    public MonoConcurrentDictionary()
    {
    }

    /// <summary>
    /// 获取或者设置指定的值到字典中。
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public new TValue? this[TKey key]
    {
        get
        {
            return Get(key);
        }
        set
        {
            if (value == null)
                throw new ArgumentNullException(nameof(value));

            AddOrUpdate(key, value, (oldKey, oldValue) =>
            {
                return value;
            });
        }
    }

    /// <summary>
    /// 获得项。
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public TValue? Get(TKey key)
    {
        var status = TryGetValue(key, out TValue? value);

        if (!status)
        {
            return default;
        }

        return value;
    }

    /// <summary>
    /// 增加项。
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public bool Add(TKey key, TValue value)
    {
        return TryAdd(key, value);
    }

    /// <summary>
    /// 移除项。
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public bool Remove(TKey key)
    {
        return TryRemove(key, out _);
    }

    /// <summary>
    /// 值列表中是否存在指定值。
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public bool ContainsValue(TValue value)
    {
        return Values.Contains(value);
    }
}
